/* $RCSFile: FolderDataType.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/UI/DataTypes/FolderDataType.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:29  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.IO;
using System.ComponentModel;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;

using Telerik.Web.UI;

namespace AddonNice.UI.DataTypes
{
	/// <summary>
	/// Implements a DropDownList with a list of directories 
	/// and a TextBox to add and create a new directory.
	/// </summary>
	public class FolderDataType : BaseDataType
	{
		private string _dataValueField;
		private string _dataTextField;
		private string _baseDirectory;
		private string _defaultDirectory;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="baseDirectory">Create if not exists</param>
		/// <param name="defaultDirectory">Create if not exists</param>
		public FolderDataType(string baseDirectory, string defaultDirectory)
		{
            if (DataTypeTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType Ctor BEG baseDirectory:{0}", baseDirectory), DataTypeTraceSwitch.Sw.Info);
            char[] achar        =   new char[]{'\\'};
			_baseDirectory		=	baseDirectory.TrimEnd(achar);
			_defaultDirectory	=	defaultDirectory.TrimStart(achar);
			InnerDataType		=	PropertiesDataType.List;
            ResetDirectories();
        }

		void ResetDirectories()
		{
			if (_defaultDirectory != null) 
			{
				try
				{
					// CS 12/5/7 for portalsettings construction default image dir : if (!Directory.Exists(baseDirectory + "/" + defaultDirectory)) 
					if (!Directory.Exists(Path.Combine(_baseDirectory,_defaultDirectory))) 
					{
                        if (!Directory.Exists(_baseDirectory))
                        {
                            if (DataTypeTraceSwitch.Sw.TraceVerbose)
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType ResetDirectories Creating baseDirectory:{0}", _baseDirectory), DataTypeTraceSwitch.Sw.Info);
                            Directory.CreateDirectory(_baseDirectory);
                        }
                        string dTarget  =   Path.Combine(_baseDirectory,_defaultDirectory);
                        if (DataTypeTraceSwitch.Sw.TraceVerbose)
                            Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType ResetDirectories Creating DefaultDirectory:{0}", dTarget), DataTypeTraceSwitch.Sw.Info);
						Directory.CreateDirectory(dTarget);
					}
				}
				catch(Exception ex)
				{
                    string msg  =   string.Format("[E]FolderDataType ResetDirectories Cannot create the default directory baseDirectory:{0}, baseDirectory:{1,} ex : {2}",
                                _baseDirectory,  _defaultDirectory, ex);
					if ( DataTypeTraceSwitch.Sw.TraceError )
                        Trace.WriteLine(msg,DataTypeTraceSwitch.Sw.Info);
					throw new ArgumentException(msg, "FolderDataType");
				}
			}
            if (DataTypeTraceSwitch.Sw.TraceVerbose)
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType ResetDirectories END BaseDirectory:{0}", _baseDirectory), DataTypeTraceSwitch.Sw.Info);
		}

        /// <summary>
        /// Return a physical path to the chosen folder
        /// </summary>
        public override string FullPath
        {
            get
            {
                return Path.Combine(_baseDirectory,Val);
            }
        }
		
        protected override void InitializeComponents()
		{
			if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType InitializeComponents BEG ReadOnly: {0}", ReadOnly),DataTypeTraceSwitch.Sw.Info);
			FolderInput fi      =   new FolderInput();
            fi.Width            =   controlWidth;
            if ( ReadOnly )
                fi.Enabled      =   false;
            innerControl        =   fi;
            _IsInitialized      =   true;
		}
		
		public override string baseDirectory
		{
			get
			{
				return _baseDirectory;
			}
			set
			{
				_baseDirectory = value;
                ResetDirectories();
			}
		}

		public override string DataValueField
		{
			get
			{
				return _dataValueField;
			}
			set
			{
				_dataValueField = value;
			}
		}

		public override string DataTextField
		{
			get
			{
				return _dataTextField;
			}
			set
			{
				_dataTextField = value;
			}
		}
        
		public override object DataSource
		{
			get
			{
			    ArrayList result = new ArrayList();
			    foreach (DirectoryInfo di in new DirectoryInfo(_baseDirectory).GetDirectories()) 
			    {
                    if (DataTypeTraceSwitch.Sw.TraceVerbose)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType DataSource Adding Directory:{0}", di.Name), DataTypeTraceSwitch.Sw.Info);
				    result.Add(new ListItem(di.Name, di.Name));
			    }
			    InnerDataSource     = result;
                if (DataTypeTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType DataSource END Cnt:{0}", result.Count), DataTypeTraceSwitch.Sw.Info);
				return InnerDataSource;
			}
			set
			{
				InnerDataSource = value;
			}
		}

		public override string Val
		{
			get
			{
				return innerValue;
			}
			set
			{
				innerValue = value;
			}
		}

        public override Unit controlWidth
        {
            get
            {
                return base.controlWidth;
            }
            set
            {
                base.controlWidth       =   value;
                if (_IsInitialized)
                {
                    FolderInput panel   =   (FolderInput)EditControl;
                    panel.Width         =   value;
                }
            }
        }

        public override void DataBind()
        {
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]FolderDataType DataBind BEG.",DataTypeTraceSwitch.Sw.Info);
			try
			{
				FolderInput panel       = (FolderInput) EditControl;
                panel.Width             =   controlWidth;
                panel.DataTextField     =   DataTextField;
                panel.DataValueField    =   DataValueField;
                panel.DataSource        =   DataSource;
                panel.DataBind();
                panel.SelectedValue     =   Val;
			}
			catch (Exception ex)
			{
                if ( DataTypeTraceSwitch.Sw.TraceError )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FolderDataType DataBind ex: {0}",ex),DataTypeTraceSwitch.Sw.Info);
                throw;
			}
            if ( DataTypeTraceSwitch.Sw.TraceVerbose )
                Trace.WriteLine("[V]FolderDataType DataBind END.",DataTypeTraceSwitch.Sw.Info);
        }

        public override Control EditControl
		{
			get
			{
				if ( innerControl == null  )
					InitializeComponents();
				return innerControl;
			}
			set
			{
                if (DataTypeTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine("[V]FolderDataType EditControl SET BEG.", DataTypeTraceSwitch.Sw.Info);
				if (value is FolderInput)
				{
					innerControl        =   value;
                    FolderInput panel   =   (FolderInput)innerControl;
                    string newFolder    =   panel.NewFolder;
                    if (DataTypeTraceSwitch.Sw.TraceVerbose)
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType EditControl SET newFolder: {0}.",newFolder ), DataTypeTraceSwitch.Sw.Info);
                    if ( !string.IsNullOrEmpty( newFolder) )
                    {
                        try
                        {
                            string path =   Path.Combine(_baseDirectory, newFolder);
                            if (!Directory.Exists(path))
                            {
                                if (DataTypeTraceSwitch.Sw.TraceVerbose)
                                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType EditControl SET Creating path: {0}.",path), DataTypeTraceSwitch.Sw.Info);
                                Directory.CreateDirectory(Path.Combine(_baseDirectory, newFolder));
                            }
                            innerValue = newFolder;
                        }
                        catch (Exception ex)
                        {
                            if (DataTypeTraceSwitch.Sw.TraceError)
                                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]FolderDataType EditControl SET unable to create dir baseDirectory:{0}, Folder : {1}, ex: {2}", _baseDirectory,newFolder, ex), DataTypeTraceSwitch.Sw.Info);
                        }
                    }
                    else
                    {
                         innerValue = panel.SelectedValue;
                    }
                if (DataTypeTraceSwitch.Sw.TraceVerbose)
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]FolderDataType EditControl SET END innerValue: {0}.",innerValue), DataTypeTraceSwitch.Sw.Info);
				return;
				}
				string str	=	string.Format("[E]FolderDataType EditControl Set: a Panel value is required, a '{0}' is given.",value.GetType().Name);
				if ( DataTypeTraceSwitch.Sw.TraceError )
                    Trace.WriteLine(str,DataTypeTraceSwitch.Sw.Info);
				throw new ArgumentException(str, "EditControl");
			}
		}

	}
}